$(document).ready(function () {
    var $ajaxForm = $('#ajax-form'),
        $response = $('#response'),
        noresults = 'There were no search results.',
        failed = 'Sorry, but teh request could not ' +
            'reach its destination. Try again later.';

    var response = function (json) {
        var output = '';
        if (json && json.length) {
            output += '<ol>';
            $.each(json, function (index, value) {
                output += buildItem(value);
            });
            output += '</ol>';
        } else {
            output += noresults;
        }
        $response.html(output);
    }
    var api = {};

    $ajaxForm.on('submit', function (e) {
        e.preventDefault();

        $response.empty();

        var search = $('#title').val();
        if (search == '') {
            return;
        }

        $response.addClass('loading');

        if (!api[search]) {
            api[search] = $.ajax({
                type: "get",
                url: "http://book.learningjquery.com/api/",
                data: {
                    title: search
                },
                dataType: "jsonp",
                timeout: 15000
            });
        }

        api[search]
            .done(response)
            .fail(function () {
                $response.html(failed);
            }).always(function () {
                $response.removeClass('loading');
            });
    });

    var searchTimeout,
        searchDelay = 300;

    $('#title').on('keyup', function () {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function () {
            $ajaxForm.triggerHandler('submmit');
        }, searchDelay);
    });

    $.ajaxSetup({
        accepts: {
            yaml: 'application/x-yaml, text/yaml'
        },
        contents: {
            yaml: /yaml/
        },
        converters: {
            'text yaml': function (textValue) {
                var result = YAML.eval(textValue);
                var errors = YAML.getErrors();
                if (errors.length) {
                    throw errors;
                }
                return result;
            }
        }
    });

    $.getScript('yaml.js').done(function () {
        $.ajax({
            url: 'categories.yml',
            dataType: 'yaml',
        }).done(function (data) {
            var cats = '';
            $.each(data, function (category, subcategories) {
                cats += '<li><a href="#">' + category + '</a></li>';
            });

            $(document).ready(function () {
                var $cats = $('#categories').removeClass('hide');
                $('<ul></ul>', { html: cats }).appendTo($cats);
            });
        });
    });
});